import win32com #打包需要
import urllib.request
import urllib.parse
import json
from tkinter import *
import tkinter.messagebox

def selectText(event):
    contentText.tag_add(SEL, "1.0", END)
    return 'break'

def translate():
    keyWords = inputEntry.get()
    if keyWords.strip() == "":
        tkinter.messagebox.showinfo("提示", "请输入要翻译的词语！")
        return


    url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=http://www.youdao.com/'
    data = {}

    data['type'] = 'AUTO'
    data['i'] = keyWords
    data['doctype'] = 'json'
    data['xmlVersion'] = '1.8'
    data['keyfrom'] = 'fanyi.web'
    data['ue'] = 'UTF-8'
    data['action'] = 'FY_BY_CLICKBUTTON'
    data['typoResult'] = 'true'

    data = urllib.parse.urlencode(data).encode('utf-8')
    response = urllib.request.urlopen(url, data)
    html = response.read().decode('utf-8')
    result = json.loads(html)
    text = result['translateResult'][0][0]['tgt']
    print(result['translateResult'])
    #tipTitle = "词语 [ " + keyWords + " ] 翻译的结果是："

    #resultLabel.configure(text = tipTitle)
    contentText.delete(1.0, END) #先清空
    contentText.insert(1.0, text)

root = Tk()

root.title("欧茄翻译器")
root.geometry("+10+10")

# topFrame
topFrame = Frame(root, width = 50, height = 20, pady = 5)
#topFrame.propagate(False)
topFrame.pack()

inputLabel = Label(topFrame, width = 50, text = "请输入要翻译的词")
inputLabel.pack()

inputEntry = Entry(topFrame, width = 50)
inputEntry.pack()

# mainFrame
mainFrame = Frame(root, width = 50, height = 20, pady = 5)
mainFrame.pack()

inputButton = Button(mainFrame, width = 50, text = "翻译", fg = "#ffffff", bg = "#007700", command = translate)
inputButton.pack()

# bottomFrame
bottomFrame = Frame(root, width = 50, height = 50, pady = 5)
bottomFrame.pack()

#resultLabel = Label(bottomFrame, width = 50)
#resultLabel.pack()

##########文本框与滚动条start
vScrollBar = Scrollbar(bottomFrame, orient = VERTICAL)  #文本框-竖向滚动条
#hScrollBar = Scrollbar(bottomFrame, orient = HORIZONTAL)  #文本框-横向滚动条
#contentText = Text(bottomFrame, width = 48, height = 15, yscrollcommand = vScrollBar, xscrollcommand = hScrollBar, wrap = 'none')  #设置滚动条-不换行
contentText = Text(bottomFrame, width = 48, height = 15, yscrollcommand = vScrollBar, wrap = WORD)  #设置滚动条-不换行
#滚动事件
vScrollBar.config(command = contentText.yview)
#hScrollBar.config(command = contentText.xview)

#布局
vScrollBar.pack(fill = "y", expand = 0, side = RIGHT, anchor = N)
#hScrollBar.pack(fill = "x", expand = 0, side = BOTTOM, anchor = N)
contentText.pack(fill = "x", expand = 1, side = LEFT) 

#绑定事件  
contentText.bind("<Control-Key-a>", selectText)
#contentText.bind("<Control-Key-A>", selectText)
##########文本框与滚动条end  

root.mainloop()